package edu.indiana.d2i.app.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

public class SolrTermFrequencyResult {
	// <word1, < <frequency>, <positions> >>
	private List<HashMap<String, ArrayList<ArrayList<Integer>>>> wordList = null;
	
	private void setWordFrequency(String word, XMLStreamReader parser) throws XMLStreamException {
		// get frequency and offset
		ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
		ArrayList<Integer> tf = new ArrayList<Integer>();
		ArrayList<Integer> offset = new ArrayList<Integer>();
		int iterCount = 0;
		while (iterCount < 2) {
			parser.nextTag(); // jump to next tag
			String attributeValue = parser.getAttributeValue(null, "name");
			if (attributeValue != null) {
				if (attributeValue.equals("tf")) {
					tf.add(Integer.valueOf(parser.getElementText()));
					iterCount++;
				}
				if (attributeValue.equals("positions")) {
					parser.nextTag(); // jump to start element
					while ( !(parser.getLocalName().equals("lst")) ) {
						offset.add(Integer.valueOf(parser.getElementText()));
						parser.nextTag(); // jump to start element
					}
					iterCount++;
				}
			}
		}
		list.add(tf);
		list.add(offset);		
		
		HashMap<String, ArrayList<ArrayList<Integer>>> map = 
			new HashMap<String, ArrayList<ArrayList<Integer>>>();
		map.put(word, list);
		wordList.add(map);
	}

	/**
	 * <lst name="termVectors">
	 * 		<lst name="doc-72">
	 * 			<str name="uniqueKey">inu.32000014448296</str>
	 * 			<lst name="ocr">
	 * 				<lst name="won">
	 * 					<int name="tf">14</int>
	 * 				</lst>
	 * 				<lst name="positions">
	 * 					<int name="position">9369</int>
	 * 					<int name="position">19163</int>
	 * 				</lst>
	 * 			</lst>
	 * 		</lst>
	 * </lst>
	 *
	 */
	private void setResult(String url, String regEx) {
		try {
			// get the stream
			URL u = new URL(url);
			InputStream in = u.openStream();
			XMLInputFactory factory = XMLInputFactory.newInstance();
			XMLStreamReader parser = factory.createXMLStreamReader(in);

			// parse the stream
			boolean bTermVector = false;
			boolean bOcr = false;
			while (parser.hasNext()) {
				int event = parser.next();				
				switch (event) {
				case XMLStreamConstants.START_ELEMENT:
					String attributeValue = parser.getAttributeValue(null, "name");
					if (attributeValue != null) {
						if (bTermVector && bOcr) {
							// get word frequency
							if (attributeValue.matches(regEx)) {
								setWordFrequency(attributeValue, parser);
							}
						}
						else if (attributeValue.equals("termVectors")) {
//							System.out.println(attributeValue);
							bTermVector = true;
						}
						else if (attributeValue.equals("ocr")) {
//							System.out.println(attributeValue);
							bOcr = true;
						}
					}
					break;
				case XMLStreamConstants.CHARACTERS:
//					if (inHeader > 0)
//					System.out.println(parser.getLocalName());
//					System.out.println(parser.getText());
//					System.out.println(parser.getText());
					break;
				} // end switch
			} // end while
			parser.close();

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (XMLStreamException e) {
			e.printStackTrace();
		}

	}

	public List<HashMap<String, ArrayList<ArrayList<Integer>>>> getWordList() {
		return wordList;
	}

	public SolrTermFrequencyResult(String url, String regEx) {
		wordList = new ArrayList<HashMap<String, ArrayList<ArrayList<Integer>>>>();
		setResult(url, regEx);
	}

	public static void main(String[] args) {
		SolrTermFrequencyResult result = new SolrTermFrequencyResult(
				"http://coffeetree.cs.indiana.edu:8888/solr/select/?q=war+AND+id%3A%22inu.32000011575976%22&version=2.2&start=0&rows=10&indent=on&qt=tvrh&tv.tf=true&tv.positions=true", 
				"w.*");
		List<HashMap<String, ArrayList<ArrayList<Integer>>>> wordList = result.getWordList();
		for (HashMap<String, ArrayList<ArrayList<Integer>>> hashMap : wordList) {
			for (String str : hashMap.keySet()) {
				System.out.print(str + "\t");
				System.out.print(hashMap.get(str).get(0).get(0) + "\t");
				for (Integer offset : hashMap.get(str).get(1)) {
					System.out.print(offset + "\t");
				}
				System.out.println();
			}
		}
		
//		String test = "swor";
//		System.out.println(test.matches("w.*"));
	}
}
